define(function(require, exports, module){
  'use strict';
  var $ = require('jquery');
  // require('bootstrapjs')($);
  require('seajs/plugs/jquery.md5')($);
  require('seajs/plugs/jquery.cookie')($);

  window.isUnnormalExitDispatcher = true;
  window.onload = function(){
    var _const = require('seajs/fn/fnConst');
    var Sidebar = require('seajs/fn/fnSidebar');
    var fnData = require('seajs/fn/fnData');
    var FnMap = require('seajs/fn/fnMap');
    var FnTemporaryGroup=require('seajs/fn/fnTemporaryGroup');

    var FnUtils = require('seajs/fn/fnUtils');
    var uploadPhoto = require('seajs/fn/fnUploadPhoto');
    var fnSocket, _ws, sidebar, fnMap, pttKey, userCode,
    cmpid, uid, passport, key, defaultGid, cmpData,uname,fnTemporaryGroup;
    var initComponent = function(uid){
      fnMap = new FnMap();
      sidebar = new Sidebar(uid, cmpData);
      fnMap.initAmap(13);

     //slidebar set
      sidebar.setTemporaryGroup(temporaryGroup);
      sidebar.setMap(fnMap);

      onEventInit(sidebar, fnMap);

      // socket
      if(cmpid && uid && passport){
        fnSocket = require('seajs/fn/fnSocket');
        _ws = new fnSocket(cmpid, uid, passport, key);
        _ws.setShowMarkerMap(fnMap.markerMap);
        _ws.setSlidebar(sidebar);
        _ws.rtpWs.setPttKeyboard(pttKey);
        fnMap.setWs(_ws);
        mapShowInit(sidebar, fnMap);
        settingInit();
        forbiddenInput();

      }
    };

    // EVENT
    function onEventInit(sidebarContainer, mapContainer){
      // radio 事件
      sidebarContainer.groupRadioOnChanged();
      //设置
      $('#setting').on('click', function(){
        $('#settingModal').modal('show');
      });

      //退出
      $('#dispatcherLogout').on('click', function(){
        $('#exitModal').modal('show');
      });

      //修改密码
      $('#updatePwd').on('click', function(){
        $('#updatePwdModal').modal('show');
      });
      // window.onbeforeunload = function() {
      //   return true;
      // };
    }

    /***************************************************************************
    ***************************** initData by lxl*******************************
    ***************************************************************************/
    function alertInit(){
      $('#repeatLoginLogoutConfirm').on('click', function(){
        FnUtils.exitDispatcher(_ws);
        location.href = 'login.html';
      });
    }
    //prevent scroll pullDown
    function cancelSpace(e){
      var e = e|| window.event;
      var elm = e.srcElement || e.target;
      var key = e.keyCode || e.charCode;
      if(key == 32){
        if(elm.tagName.toLowerCase()=="input" && elm.type.toLowerCase()=="text" || elm.tagName.toLowerCase() == "textarea"){
          return;
        }
        if(window.event){
          e.returnValue = false;
        }
        else{
          e.preventDefault();
        }
      }
    }
    document.onkeypress=cancelSpace;
    /** update pwd**/
    var showError = function(msg){
      $('#settingInfo > h6').html(msg).removeAttr('vis-hid');
    }
    var showSuccess = function(msg){
      $('#success_bar_info').html(msg);
      $("#success_bar").css('display', 'block');
    }
    var hideSuccess = function(fun){
      fun();
      setTimeout(function(){
        $("#success_bar").css('display', 'none');
      }, 5000);
    }
    function settingInit(){
      var boardkey = require('seajs/plugs/boardKey');
      var _data = {
        userid: uid,
        uid: uid,
        timestamp: FnUtils.getUnixTime(),
        userType: _const.DEVICE.DISPATCHER,
        companyid: cmpid,
        key: key
      };
      FnUtils.commonPost('app/pttQuery.do', _data, function(rlt){
        if(rlt.status === _const.HTTP.RES_STATUS.SUCCESS){
          if(!isNaN(rlt.body.pttstr)){
            pttKey = parseInt(rlt.body.pttstr);
            $('#pttKeyName').val(boardkey.getKeyName(pttKey));
            $('#pttKeyValue').val(pttKey);
            _ws.rtpWs.setPttKeyboard(pttKey);
          }
        }else{
          showError(rlt.error.message);
        }
      }, function(e){
        showError(e.message);
      });

      $('#settingConfirm').on('click', function(){
        var pttValue = $('#pttKeyValue').val();
        var _data = {
          uid: uid,
          pttStr: pttValue,
          userid: uid,
          userType: _const.DEVICE.DISPATCHER,
          timestamp: FnUtils.getUnixTime(),
          companyid: cmpid,
          key: key
        };
        FnUtils.commonPost('app/pttModify.do', _data, function(rlt){
          if(rlt.status === _const.HTTP.RES_STATUS.SUCCESS){
            pttKey = parseInt(pttValue);
            showSuccess('修改成功!');
            hideSuccess(function(){
              $('#settingModal').modal('hide');
            });
            _ws.rtpWs.setPttKeyboard(pttKey);
          }else{
            showError(rlt.error.message);
          }
        }, function(e){
          showError(e.message);
        });
      });

      $('#pttKeyName').on('keyup', function(event){
        if(event.which === 8){//判断是退格键，则直接清空当前input
          $('#pttKeyName').val('');
          $('#pttKeyValue').val('');
          $('#settingConfirm').attr('disabled', 'disabled');
        }else{
          var pttKeyName = boardkey.getKeyName(event.which);
          if(!pttKeyName){
            pttKey = 32;
            pttKeyName = 'Spacebar';
          }
          if(pttKey ==  event.which){
            $('#settingConfirm').attr('disabled', 'disabled');
          }else{
            $('#settingConfirm').removeAttr('disabled');
          }
          $('#pttKeyName').val(pttKeyName);
          $('#pttKeyValue').val(event.which);
        }
      });
      $("#pttKeyName").on('click', function(event){
        $("#settingInfo > h6").html('error').addClass('vis-hid');
      });

      $('#settingModal').on('hide.bs.modal', function () {
        var pttKeyName = boardkey.getKeyName(pttKey);
        if(!pttKeyName){
          pttKey = 32;
          pttKeyName = 'Spacebar';
        }
        $('#pttKeyName').val(pttKeyName);
        $('#pttKeyValue').val(pttKey);
        $('#settingConfirm').attr('disabled', 'disabled');
      });
    }

    /**
     * input不触发RTP
     */
    function forbiddenInput(){
      $('input').on('focus', function(){
        _ws.rtpWs.offPttKey();
      });
      $('input').on('blur', function(){
        _ws.rtpWs.onPttKeyDown();
        _ws.rtpWs.onPttKeyUp();
      });
    }

    function updateInit(){
      var showError = function(msg){
        $('#updatePwdInfo>h6').html(msg).removeClass("vis-hid");
        $("#updatePwdConfirm").attr('disabled','disabled');
      };
      var hidError = function(){
        $('#updatePwdInfo>h6').addClass("vis-hid");
        $("#updatePwdConfirm").removeAttr("disabled");
      };
      var checkForm = function(){
        var oPwd = $('#originPwd').val();
        var newPwd1 = $('#newPwd1').val();
        var newPwd2 = $('#newPwd2').val();
        if(oPwd.length === 0){
          showError('请输入原密码!');
        }else if(oPwd.length < 6 || oPwd.length > 16){
          showError('原密码为6-16位字符!');
        }else if(newPwd1.length === 0){
          showError('请输入新密码!');
        }else if(newPwd1.length < 6 || newPwd1.length > 16){
          showError('新密码为6-16位字符!');
        }else if(oPwd === newPwd1){
          showError('新密码与原密码不能相同!');
        }else if(newPwd2.length === 0){
          showError('请确认新密码!');
        }else if(newPwd2.length < 6 || newPwd2.length > 16){
          showError('确认密码为6-16位字符!');
        }else if(newPwd2 !== newPwd1){
          showError('两次密码输入不一致!');
        }else{
          hidError();
        }
      }

      $('#originPwd').on('blur', function(){
        checkForm();
      }).on('input', function(){
        checkForm();
      }).on('propertychange', function(){
        checkForm();
      });

      $('#newPwd1').on('blur', function(){
        checkForm();
      }).on('input', function(){
        checkForm();
      }).on('propertychange', function(){
        checkForm();
      });

      $('#newPwd2').on('blur', function(){
        checkForm();
      }).on('input', function(){
        checkForm();
      }).on('propertychange', function(){
        checkForm();
      });
      $('#updatePwdConfirm').on('click', function(){
        var oPwd = $('#originPwd').val();
        var newPwd1 = $('#newPwd1').val();
        var newPwd2 = $('#newPwd2').val();
        if($.md5(oPwd) !== passport){
          showError('原密码错误!');
        }else{
          hidError('error');
          var _data = {
            userid: uid,
            userCode: userCode,
            oldPassword: $.md5(oPwd),
            password: $.md5(newPwd1),
            confirmPassword: $.md5(newPwd2),
            timestamp: FnUtils.getUnixTime(),
            userType: _const.DEVICE.DISPATCHER,
            companyid: cmpid,
            key: key
          };
          FnUtils.commonPost('app/passwordEdit.do', _data, function(rlt){
            if(rlt.status === _const.HTTP.RES_STATUS.SUCCESS){
              showSuccess('密码修改成功，3S后跳转至登录界面!');
              $('#updatePwdModal').modal('hide');
              setTimeout(function(){
                location.href = 'login.html';
              }, 3000);
            }else{
              showError(rlt.error.message);
            }
          }, function(e){
            showError(e.message);
          });
        }
      });

      $('#updatePwdModal').on('hide.bs.modal', function () {
        $('#originPwd').val('');
        $('#newPwd1').val('');
        $('#newPwd2').val('');
        $('#updatePwdInfo>h6').addClass("vis-hid");
        //$("#updatePwdConfirm").removeAttr('disabled');
      });
    }

    var logoutInit = function(){
      $('#logoutConfirm').on('click', function(){
        FnUtils.exitDispatcher(_ws);
        FnUtils.logout(uid, cmpid, key, function(data){
        }, function(e){
          console.log(e);
        });
        location.href = 'login.html';
      });
    }

    var mapShowInit = function(slidebar, fnMap){
      for(var m in slidebar.memberMap.map){
          fnMap.showMarkerPut(slidebar.memberMap.get(m));
      }
      var showMap = function(){
        var statusShow = parseInt($('#member-status-select').val());
        var talkGroupId = parseInt($('#talk-group-select').val());
        for(var n in slidebar.memberMap.map){
          fnMap.showMarkerRemove(slidebar.memberMap.get(n).memberId);
        }
        if(talkGroupId === 0){
          var membersShow = slidebar.memberMap.values();
          for(var key in slidebar.memberMap.map){
            if(statusShow === 0 || slidebar.memberMap.get(key).status === statusShow){
              fnMap.showMarkerPut(slidebar.memberMap.get(key));
            }
          }
        }else{
          var groupShow = slidebar.groupMap.get(talkGroupId);
          for(var i in groupShow.members.online){
            var memberId = groupShow.members.online[i].memberId;
            if(statusShow === 0 || slidebar.memberMap.get(memberId).status === statusShow){
              fnMap.showMarkerPut(slidebar.memberMap.get(memberId));
            }
          }
          for(var j in groupShow.members.inOther){
            var memberId = groupShow.members.inOther[j].memberId;
            if(statusShow === 0 || slidebar.memberMap.get(memberId).status === statusShow){
              fnMap.showMarkerPut(slidebar.memberMap.get(memberId));
            }
          }
          for(var k in groupShow.members.offline){
            var memberId = groupShow.members.offline[k].memberId;
            if(statusShow === 0 || slidebar.memberMap.get(memberId).status === statusShow){
              fnMap.showMarkerPut(slidebar.memberMap.get(memberId));
            }
          }
        }
        if(fnMap.showMemberMap.size() > 0){
          var isInit = false, swLat = 0, swLng = 0, neLat = 0, neLng = 0;
          for(var gid in fnMap.showMemberMap.map){
            if(!isInit){
              swLat = fnMap.showMemberMap.get(gid).position[1];
              swLng = fnMap.showMemberMap.get(gid).position[0]; 
              neLat = fnMap.showMemberMap.get(gid).position[1]; 
              neLng = fnMap.showMemberMap.get(gid).position[0];
              isInit = true;
            }
            if(fnMap.showMemberMap.get(gid).position[0] < swLng){
              swLng = fnMap.showMemberMap.get(gid).position[0];
            }
            if(fnMap.showMemberMap.get(gid).position[0] > neLng){
              neLng = fnMap.showMemberMap.get(gid).position[0];
            }
            if(fnMap.showMemberMap.get(gid).position[1] < swLat){
              swLat = fnMap.showMemberMap.get(gid).position[1];
            }
            if(fnMap.showMemberMap.get(gid).position[1] > neLat){
              neLat = fnMap.showMemberMap.get(gid).position[1];
            }
          }
          var bound = new AMap.Bounds(new AMap.LngLat(swLng, swLat), new AMap.LngLat(neLng, neLat));
          fnMap.map.setBounds(bound);
        }
      }
      $('#talk-group-select').on('change',function(){
        showMap();
      });
      $('#member-status-select').on('change',function(){
        showMap();
      });
    }

	  function init(){
      userCode = FnUtils.getQueryString('userCode');
      cmpid = FnUtils.getQueryString('companyId');
      uid = FnUtils.getQueryString('userid');
      passport = FnUtils.getQueryString('passport');
      key = FnUtils.getQueryString('userToken');
      defaultGid = FnUtils.getQueryString('defaultGid');
      $('#dispatcherName').html(unescape(FnUtils.getQueryString('userName')));
//
      alertInit();
      updateInit();
      logoutInit();
      
      if(cmpid && uid && passport && key){
        uid = parseInt(uid);
        cmpid = parseInt(cmpid);
        FnUtils.groupMemberLocationsQuery(uid, cmpid, key, function(data){
          if(data.status === _const.HTTP.RES_STATUS.SUCCESS){
            cmpData = fnData.formatData(data, uid, defaultGid);
            initComponent(uid);

          }else{
            $('.repeat-login-bar').html(data.error.message + ",点击确定返回登陆页!");
            $('#returnLoginModal').modal('show');
          }
        }, function(e){
          $('.repeat-login-bar').html(e.statusText + ",点击确定返回登陆页!");
          $('#returnLoginModal').modal('show');
        });
      }else{
        $('.repeat-login-bar').html(data.error.message + ",点击确定返回登陆页!");
        $('#returnLoginModal').modal('show');
      }
    }
  	init();
    /**********************************************************************************************************
     *********************************************** 以下拍传功能 ***********************************************
     **********************************************************************************************************/


    //点击标题
    $(document).on('click','#message-pop .message-title',function(e){
      e.preventDefault();
      var lat=$(this).attr('data-lat');
      var log=$(this).attr('data-log');
      fnMap.photoSiteMarker(log,lat);
      if($(this).attr('data-i')=='0'){
        $(this).parent().parent().find('.message-detail').slideToggle();
        setTimeout(function(){
          if($(this).parent().parent().find('.message-detail').css('display')=='none'){
            $('.pic-site').fadeOut(200);
            $('.pic-site1').html('');
          };
        }.bind(this),500);
        $($(this).parent().parent().find('.unread')).removeClass('unread').addClass('hasread');
      }else{
        var numI=$(this).attr('data-i');
        arrowDerection(numI);
        //if($('#message-pop .ul li:nth-child('+numI+') .message-detail').css('display')=='none'){
        //  $('#message-pop .ul li:nth-child('+numI+') .down-arrow').removeClass('pull-down').addClass('pull-up');
        //  $('.pic-site1').html('');
        //}else if($('#message-pop .ul li:nth-child('+numI+') .message-detail').css('display')=='block'){
        //  $('#message-pop .ul li:nth-child('+numI+') .down-arrow').removeClass('pull-up').addClass('pull-down');
        //  setTimeout(function(){
        //    $('.pic-site').fadeOut(100);
        //  },100);
        //}
        $('#message-pop .ul li:nth-child('+numI+') .message-detail').slideToggle(100);
        $('#message-pop .ul li:nth-child('+numI+') .unread').removeClass('unread').addClass('hasread');
        //单个消息请求
        var imgid=$(this).attr('data-imgId');
        var _data={
          'userid':uid,
          'companyid':cmpid,
          'userType':_const.DEVICE.DISPATCHER,
          'timestamp':FnUtils.getUnixTime(),
          'messageId':imgid,
          'key':key
        };
        if(!$('#message-pop .ul li:nth-child('+numI+') div[class*=image]').html()){
          FnUtils.commonPost('app/getMessageInfo.do',_data,function(rlt){
            if(rlt.status===_const.HTTP.RES_STATUS.SUCCESS){
              var data=JSON.parse(rlt.body);
              console.log(data);
              var imgList='',imgClass;
              if(data.fileInfoList.length==1){
                imgClass='image3';
              }else if(data.fileInfoList.length==2){
                imgClass='image2';
              }else{
                imgClass='image1';
              };
              //$('#message-pop .ul li:nth-child('+numI+') .message-title').html(data.bucket+'发来消息');
              $('#message-pop .ul li:nth-child('+numI+') .push-time').html(FnUtils.unixTimeFormat(data.uploadTime).slice(-11));
              $('#message-pop .ul li:nth-child('+numI+') .message-content').html(data.theme);
              $('#message-pop .ul li:nth-child('+numI+') .detail-describe').html(data.remark);
              for(var j=0;j<data.fileInfoList.length;j++){
                imgList+="<img src="+data.fileInfoList[j].smallFileUrl+" data-url="+data.fileInfoList[j].fileUrl+" />"
              };
              $('#message-pop .ul li:nth-child('+numI+') div[class*=image]').html(imgList).attr('class',imgClass);
              $('#message-pop .ul li:nth-child('+numI+') .detail-site span').html(data.uploadAddress);
            }else{
              showError(oss.error.message);
            }
          },function(e){
            showError(e.message);
          });
        }
      }
    });
    //click pull-down icon

    function arrowDerection(i){
      //console.log($('#message-pop .ul li:nth-child('+i+') .message-detail').is(':visible'));
      if($('#message-pop .ul li:nth-child('+i+') .message-detail').css('display')=='none'){
        $('#message-pop .ul li:nth-child('+i+') .down-arrow').removeClass('pull-down').addClass('pull-up');
        $('.pic-site1').html('');
      }else if($('#message-pop .ul li:nth-child('+i+') .message-detail').css('display')=='block'){
        $('#message-pop .ul li:nth-child('+i+') .down-arrow').removeClass('pull-up').addClass('pull-down');
        setTimeout(function(){
          $('.pic-site').fadeOut(100);
        },100);
      }
    };
    $(document).on('click','#message-pop .down-arrow',function(e){
      e.preventDefault();

      var target=$(this).parent().parent().find('.message-title');
      var lat=target.attr('data-lat');
      var log=target.attr('data-log');
      fnMap.photoSiteMarker(log,lat);
      if(target.attr('data-i')=='0'){
        target.parent().parent().find('.message-detail').slideToggle();
        setTimeout(function(){
          if($(this).parent().parent().find('.message-detail').css('display')=='none'){
            $('.pic-site').fadeOut(200);
            $('.pic-site1').html('');
          };
        }.bind(this),500);
        $($(this).parent().parent().find('.unread')).removeClass('unread').addClass('hasread');
      }else{
        var numI=target.attr('data-i');
        arrowDerection(numI);
        //if($('#message-pop .ul li:nth-child('+numI+') .message-detail').css('display')=='none'){
        //  $('#message-pop .ul li:nth-child('+numI+') .down-arrow').removeClass('pull-down').addClass('pull-up');
        //  $('.pic-site1').html('');
        //}else if($('#message-pop .ul li:nth-child('+numI+') .message-detail').css('display')=='block'){
        //  $('#message-pop .ul li:nth-child('+numI+') .down-arrow').removeClass('pull-up').addClass('pull-down');
        //  setTimeout(function(){
        //    $('.pic-site').fadeOut(100);
        //  },100);
        //}
        $('#message-pop .ul li:nth-child('+numI+') .message-detail').slideToggle(100);
        $('#message-pop .ul li:nth-child('+numI+') .unread').removeClass('unread').addClass('hasread');
        //单个消息请求
        var imgid=target.attr('data-imgId');
        var _data={
          'userid':uid,
          'companyid':cmpid,
          'userType':_const.DEVICE.DISPATCHER,
          'timestamp':FnUtils.getUnixTime(),
          'messageId':imgid,
          'key':key
        };
        if(!$('#message-pop .ul li:nth-child('+numI+') div[class*=image]').html()){
          FnUtils.commonPost('app/getMessageInfo.do',_data,function(rlt){
            if(rlt.status===_const.HTTP.RES_STATUS.SUCCESS){
              var data=JSON.parse(rlt.body);
              console.log(data);
              var imgList='',imgClass;
              if(data.fileInfoList.length==1){
                imgClass='image3';
              }else if(data.fileInfoList.length==2){
                imgClass='image2';
              }else{
                imgClass='image1';
              };
              //$('#message-pop .ul li:nth-child('+numI+') .message-title').html(data.bucket+'发来消息');
              $('#message-pop .ul li:nth-child('+numI+') .push-time').html(FnUtils.unixTimeFormat(data.uploadTime).slice(-11));
              $('#message-pop .ul li:nth-child('+numI+') .message-content').html(data.theme);
              $('#message-pop .ul li:nth-child('+numI+') .detail-describe').html(data.remark);
              for(var j=0;j<data.fileInfoList.length;j++){
                imgList+="<img src="+data.fileInfoList[j].smallFileUrl+" data-url="+data.fileInfoList[j].fileUrl+" />"
              };
              $('#message-pop .ul li:nth-child('+numI+') div[class*=image]').html(imgList).attr('class',imgClass);
              $('#message-pop .ul li:nth-child('+numI+') .detail-site span').html(data.uploadAddress);
            }else{
              showError(oss.error.message);
            }
          },function(e){
            showError(e.message);
          });
        }
      }
    });
    //点击详情
    $('#slidesway .check').click(function(){
      var lng,lat;
      var _data={
        'userid':uid,
        'companyid':cmpid,
        'userType':_const.DEVICE.DISPATCHER,
        'timestamp':FnUtils.getUnixTime(),
        'messageId':$(this).attr('data-imgid'),
        'key':key
      };
      $('#slidesway').css('right','-300px');
      FnUtils.commonPost('app/getMessageInfo.do',_data,function(rlt){
        if(rlt.status===_const.HTTP.RES_STATUS.SUCCESS){
          var data=JSON.parse(rlt.body);
          var imgList='',imgClass;
          if(data.fileInfoList.length==1){
            imgClass='image3';
          }else if(data.fileInfoList.length==2){
            imgClass='image2';
          }else{
            imgClass='image1';
          };
          lng=data.longitude;
          lat=data.latitude;
          fnMap.photoSiteMarker(lng,lat);
          $('#single-message .message-title').html(uname);
          $('#single-message .push-time').html(FnUtils.unixTimeFormat(data.uploadTime).slice(-11));
          $('#single-message .message-content').html(data.theme);
          $('#single-message .detail-describe').html(data.remark);
          for(var j=0;j<data.fileInfoList.length;j++){
            imgList+="<img src="+data.fileInfoList[j].smallFileUrl+" data-url="+data.fileInfoList[j].fileUrl+" />"
          };
          $('#single-message div[class*=image]').html(imgList).attr('class',imgClass);
          $('#single-message .detail-site span').html(data.uploadAddress);
        }else{
          showError(oss.error.message);
        }

      },function(e){
        showError(e.message);
      });

    });
    //点击查收

    /******************************************************************************************************
     *********************************************** 以上拍传功能************************************************
     * ****************************************************************************************************/
    function searchStorageList(key){
      if(!localStorage.getItem('searchStorage')){
        localStorage.setItem('searchStorage','[]');
      }
      var searchStorage=JSON.parse(localStorage.getItem('searchStorage'));

      if(searchStorage.indexOf(key)==-1){
        if(key){
          if(searchStorage.length>=10){
          searchStorage.splice(0,1);
        }
          searchStorage.push(key);
        }
      }
      //console.log(searchStorage);
      //judge searchStorage.length is greaterThen 10
      searchStorage=JSON.stringify(searchStorage);
      localStorage.setItem('searchStorage',searchStorage);
    }
    //AMap placeSearch
    function mapSearch(e){
      var key=$('#searchInput').val();
      if(!key){
        //$('.search-div .result-list').css('display','none');
        setTimeout(function(){
          $('.amap-sug-result').css('display','none');
          recordList();
          //$('.search-div .search-record').css('display','block');

        },200);
      }
      if(e.keyCode!=17&& e.keyCode!=67){
        $('.search-div .search-record').css('display','none');
      }
      if(e.keyCode==13){
        //console.log($('.search-div .search-img').attr('src'))
        $('.search-div .search-img').attr('src','images/img-loding.jpg');
        $('.amap-sug-result').css('display','none');
        if(key){$('.search-div .result-list').css('display','block');}

        var data;
        searchStorageList(key);
        AMap.plugin(['AMap.PlaceSearch','AMap.Autocomplete'],function(){
          var placeSearch=new AMap.PlaceSearch();
          placeSearch.searchNearBy(key,fnMap.map.getCenter(),30000);
          AMap.event.addListener(placeSearch,'complete',function(e){
            data= e.poiList.pois;
            var ul='<ul>';
            for(var i=0;i<data.length;i++){
              ul+="<li data-lat="
              +data[i].location.lat+" data-lng="
              +data[i].location.lng+"><p>"+(i+1)+". "
              +data[i].name+"</p><span class='add'>"
              +data[i].address+"</span></li>"
            }
            ul+="</ul>";
            $('.search-div .result-list').html(ul);
            $('.search-div .search-img').attr('src','images/frame_search_normal.png');
            var searchResultNum=$('.amap-sug-result .auto-item').length;
            if(fnMap.onlyLng){
              fnMap.map.setCenter(new AMap.LngLat(fnMap.onlyLng,fnMap.onlyLat));
              fnMap.map.setZoom(12);
            }
            if(searchResultNum==1){
              $('.search-div .result-list').css('display','none');
            }
          });
        });

      }else{
        setTimeout(function(){
          var list=$('.amap-sug-result .auto-item');
          for(var i=0;i<list.length;i++){
            var span=$(list[i]).children().text();
            var str=$(list[i]).text().slice(0,-($(list[i]).children().text().length));
            str=str.replace(key,"<span class='highlight'>"+key+"</span>");
            //console.log(str);
            var html=str+"<span class='auto-item-span'>"+span+"</span>";
            $(list[i]).html(html);
            //console.log($(list[i]).text().slice(0,-($(list[i]).children().text().length)));
            //console.log($(list[i]).children().text().length);
          }
        },500);
        $('.search-div .result-list').css('display','none');
      }
    };
    function recordList(){
      $('.search-div .search-record').css('display','block');
      var dataList=JSON.parse(localStorage.getItem('searchStorage'));
      var ul="";
      for(var i=dataList.length-1;i>=0;i--){
        ul+="<li><p>"+dataList[i]+"</p><span class='clear-storage' title='删除搜索记录'>&times;</span></li>";
      }

      $('.search-div .search-record ul').html(ul);
    }
    //input focus
    $('#searchInput').focus(function(){
     recordList();
      var key=$('#searchInput').val();
      if(key){
        $('.search-div .search-record').css('display','none');

      }
    });
    $('#searchInput').blur(function(){
      setTimeout(function(){
        $('.search-div .search-record').css('display','none');
      },300);

    });
    //record clear
    $('.search-div').on('click','.clear-storage',function(e){
      setTimeout(function(){
        $('.search-div .search-record').css('display','block');
      },320);

      var searchStorage=JSON.parse(localStorage.getItem('searchStorage'));
      var listNum=searchStorage.indexOf($(this).siblings().html());
      searchStorage.splice(listNum,1);
      searchStorage=JSON.stringify(searchStorage);
      localStorage.setItem('searchStorage',searchStorage);
      recordList();
    });
    //record click
    $('.search-div .search-record').on('click','li p',function(){
      //var v=$(this).html();
      $('#searchInput').val($(this).html());
      $('.search-div .search-record').css('display','none');
    });
    $('#searchInput').on('keyup',mapSearch);
    $('.search-div .search-img').on('click',function(){
      $('.search-div .search-img').attr('src','images/img-loding.jpg');
      $('.amap-sug-result').css('display','none');
      $('.search-div .search-record').css('display','none');
      $('.search-div .result-list').css('display','block');
      var data;
      var key=$('#searchInput').val();
      searchStorageList(key);
      AMap.plugin(['AMap.PlaceSearch'],function(){
        var placeSearch=new AMap.PlaceSearch();
        placeSearch.searchNearBy(key,fnMap.map.getCenter(),30000);
        AMap.event.addListener(placeSearch,'complete',function(e){
          data= e.poiList.pois;

          var ul='</ul>';
          for(var i=0;i<data.length;i++){
            ul+="<li data-lat="
            +data[i].location.lat+" data-lng="
            +data[i].location.lng+"><p>"+(i+1)+". "
            +data[i].name+"</p><span class='add'>"
            +data[i].address+"</span></li>"
          }
          ul+='</ul>';
          $('.search-div .result-list').html(ul);
          $('.search-div .search-img').attr('src','images/frame_search_normal.png');
        });
      });
    });
    var marker;
    $('.search-div .result-list').on('click','li',function(){
      var val=$('.search-div .result-list li p').html().split('.')[1];
      //searchStorageList(val);
      $('#searchInput').val(val);
      if(marker){
        marker.setMap(null);
      }
      $('.search-div .result-list').css('display','none');
      var lat=$(this).attr('data-lat');
      var lng=$(this).attr('data-lng');
      fnMap.map.setCenter(new AMap.LngLat(lng,lat));
      fnMap.map.setZoom(12);
      marker = new AMap.Marker({
        map:fnMap.map,
        position: [lng,lat]
      });
      marker.setMap(fnMap.map);
    });
    $('.search-div .search-img').hover(function(){
      $(this).attr('src','images/frame_search_hover.png');
    },function(){
      $(this).attr('src','images/frame_search_normal.png');
    });
    //点击其他地方 搜索结果 历史记录列表都隐藏
    $('body').click(function(e){
      if(($(e.target).attr('class')!='clear-storage')&&($(e.target).attr('id')!='searchInput')&&($(e.target).attr('class')!='search-img')){
        $('.result-list').css('display','none');
        $('.search-record').css('display','none');
      }

    });
    //头部功能列表交互
    $('#function-list').on('mousedown','li>div',function(){
      $(this).parent().css('background','#3399ff');
      $('#function-list').on('mouseup','li>div',function(){
        $(this).parent().css('background','#5bacfe');
      });
    });
    $('#function-list li>div').hover(function(){
      $(this).parent().css('background','#5bacfe');
    },function(){
      $(this).parent().css('background','#fff');
    })

    //computer .status-content height
    function statusContent(){
      var h=parseInt($('.status-content .row').css('height'));
      var parentH=parseInt($('.sidebar .nav-bottom').css('height'))-30;
      var marginTop=(parentH-h)/2;
      $('.status-content .row').css('margin-top',marginTop);
    }
    statusContent();
    $(window).resize(function() {
      statusContent();
    })


  }
  require('amap');
});